/**
 * A class for managing database connections and calls
 */
package docoffice.database;
import java.util.logging.Logger;
//Style disabled since there are several sql imports needed
import java.sql.*; // $codepro.audit.disable importStyle

/**
 * @author Ray Nosari 
 * @version $Revision: 1.0 $
 */
public class DatabaseManager {
	
	/**
	 * Field log.
	 */
	private static final Logger LOG = Logger.getLogger("DatabaseManager");;
	
	/**
	 * Field sqlCon.
	 */
	private Connection sqlCon;
	
	/**
	 * Field sqlStmt.
	 */
	private Statement sqlStmt;
	
	/**
	 * Field JDBCDriver.
	 * Object is not final due to the way it needs to be set
	 */
	private Object jdbcDriver;  // $codepro.audit.disable variableShouldBeFinal
	
	/**
	 * Constructor for DatabaseManager.
	 */
	public DatabaseManager(){
		try{
			this.jdbcDriver = getJDBCDriver();
			((Class<?>) jdbcDriver).newInstance();
			createDoctorsOfficeCon();
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Method setDoctorsOfficeCon.
	 * @throws SQLException
	 */
	public void createDoctorsOfficeCon() throws SQLException{
		this.sqlCon = DriverManager.getConnection("jdbc:mysql://localhost/doctorsoffice", 
				"root", "rockstar");
	}
	
	/**
	 * Method runUpdateQuery.
	 * @param sqlQuery String
	 */
	public void runUpdateQuery(String sqlQuery){
		LOG.info("A Create, Update, or Delete query has been run");
		try{
			boolean isConClosed = sqlCon.isClosed();
			if (!isConClosed){
				sqlStmt = sqlCon.createStatement();
				sqlStmt.executeUpdate(sqlQuery);
			}
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Method runReadQuery.
	 * @param sqlQuery String
	 * @return ResultSet
	 */
	public ResultSet runReadQuery(String sqlQuery){
		LOG.info("A Read query has been run");
		ResultSet rs = null;
		try{
			boolean isConClosed = sqlCon.isClosed();
			if (!isConClosed){
				sqlStmt = sqlCon.createStatement();
				rs = sqlStmt.executeQuery(sqlQuery);
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		return rs;
	}
	
	/**
	 * Method closeConnection.
	 */
	public void closeConnection(ResultSet rs){
		try {
			sqlCon.close();
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Method closeConnection.
	 */
	public void closeConnection(){
		try {
			sqlCon.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Method getJDBCDriver.
	 * @return Class<?>
	 * @throws ClassNotFoundException
	 */
	private static Class<?> getJDBCDriver() throws ClassNotFoundException {
		return Class.forName("com.mysql.jdbc.Driver");
	}
	
	/**
	 * Method toString.
	 * @return String
	 */
	public String toString(){
		return "This class is for managing database connections and calls";
	}
}
